// utils/http.js

let accessToken = wx.getStorageSync('accessToken') || '';
let refreshToken = wx.getStorageSync('refreshToken') || '';
let requestQueue = [];
let isRefreshing = false;

/**
 * 刷新 Token
 */
const refreshAccessToken = () => {
  return new Promise((resolve, reject) => {
    wx.request({
      url: 'https://your-api.com/auth/refresh',
      method: 'POST',
      data: { refreshToken }, // 传递 refreshToken
      success: (res) => {
        if (res.data.code === 200) {
          accessToken = res.data.accessToken;
          refreshToken = res.data.refreshToken;
          wx.setStorageSync('accessToken', accessToken);
          wx.setStorageSync('refreshToken', refreshToken);
          resolve();
        } else {
          reject(new Error('刷新 Token 失败'));
        }
      },
      fail: (err) => reject(err),
    });
  });
};

/**
 * 封装通用 request 方法（支持 GET/POST/PUT/DELETE）
 * @param {Object} options - 请求配置
 */
const request = (options) => {
  return new Promise((resolve, reject) => {
    const defaultOptions = {
      method: 'GET', // 默认 GET
      header: {
        'Content-Type': 'application/json',
        Authorization: `Bearer ${accessToken}`,
      },
    };

    const mergedOptions = { ...defaultOptions, ...options };

    wx.request({
      ...mergedOptions,
      success: (res) => {
        if (res.statusCode === 401) {
          if (!isRefreshing) {
            isRefreshing = true;
            refreshAccessToken()
              .then(() => {
                // 重试原始请求
                const retryOptions = {
                  ...mergedOptions,
                  header: {
                    ...mergedOptions.header,
                    Authorization: `Bearer ${accessToken}`,
                  },
                };
                wx.request({
                  ...retryOptions,
                  success: resolve,
                  fail: reject,
                });
                // 执行队列中的请求
                requestQueue.forEach((cb) => cb());
                requestQueue = [];
              })
              .catch((err) => {
                wx.showToast({ title: '登录已过期', icon: 'none' });
                wx.redirectTo({ url: '/pages/login/login' });
                reject(err);
              })
              .finally(() => {
                isRefreshing = false;
              });
          } else {
            // 加入队列
            requestQueue.push(() => {
              const retryOptions = {
                ...mergedOptions,
                header: {
                  ...mergedOptions.header,
                  Authorization: `Bearer ${accessToken}`,
                },
              };
              wx.request({
                ...retryOptions,
                success: resolve,
                fail: reject,
              });
            });
          }
        } else if (res.statusCode >= 200 && res.statusCode < 300) {
          resolve(res.data);
        } else {
          reject(res.data);
        }
      },
      fail: (err) => {
        wx.showToast({ title: '网络错误', icon: 'none' });
        reject(err);
      },
    });
  });
};

// 导出
export default request;